package com.lagou.edu.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.google.common.util.concurrent.RateLimiter;
import com.lagou.edu.client.AuthCodeApiService;
import com.lagou.edu.client.EmailApiService;
import com.lagou.edu.entity.AuthCode;
import com.lagou.edu.entity.Token;
import com.lagou.edu.service.AuthCodeService;
import com.lagou.edu.service.TokenService;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: yeqingyun
 * @Date: 2020/11/20 15:42
 */
@RestController
@RequestMapping("/code")
public class AuthCodeController implements InitializingBean {

    private RateLimiter rateLimiter;
    @Value("${limit.count:0.2}")
    private Double IpLimit;
    @Autowired
    private AuthCodeService authCodeService;
    @Autowired
    private TokenService tokenService;
    @Reference
    private EmailApiService emailApiService;

    @SentinelResource(value = "createCode", fallback ="createFallback")
    @RequestMapping("/create/{email}")
    public boolean create(@PathVariable("email") String email) {
        if (tokenService.isEmailExist(email)) {
            return false;
        }
        //1生成验证码
        AuthCode authCode = new AuthCode();
        authCode.setCode(UUID.randomUUID().toString());
        authCode.setEmail(email);
        authCode.setCreateTime(new Date());
        authCode.setExpireTime(new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(3600)));
        authCodeService.create(authCode);
        //2发送到邮箱
        emailApiService.sendEmail(email, authCode.getCode());
        return true;
    }

    public boolean createFallback(String email) {
        return false;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // 每秒发出5个令牌
        rateLimiter = RateLimiter.create(IpLimit);
    }
}
